package main

import (
		"fmt"
		"strings"
		"crypto/hmac"
		"crypto/sha512"
		"net/http"
		"io/ioutil"
		"encoding/json"
		"sync"
		"strconv"
		"time"
	   )


type Detail struct {
	Result   string `json:"result"`
		Last   interface{} `json:"last"`
		LowestAsk   interface{} `json:"lowestAsk"`
		HighestBid   interface{} `json:"highestBid"`
		PercentChange   interface{} `json:"percentChange"`
		BaseVolume   interface{} `json:"baseVolume"`
		QuoteVolume   interface{} `json:"quoteVolume"`
		High24hr   interface{} `json:"high24hr"`
		Low24hr   interface{} `json:"low24hr"`
}

type GateTicker struct {
	Market string
		detail Detail
}

//gate.io
//amaomaoaa  maomao86   wenxing85  13450358496
const KEY  = "43C1EC63-21D3-4AD7-A98F-40088D56B568"; 
const SECRET = "50a03f9c482ba1fab6779c87da566f03366332e94f6a7cd20c14af007867ac3a";


func getSign( params string) string {
key := []byte(SECRET)
		 mac := hmac.New(sha512.New, key)
		 mac.Write([]byte(params))
		 return fmt.Sprintf("%x", mac.Sum(nil))
}

func GetFloat(params interface{})  float64{

	var tmpdata  float64
		var err error
		switch params.(type) {
			case  float64:
				//fmt.Printf("type is float\n");
				tmpdata = params.(float64)
			case string:
					//fmt.Printf("type is string\n");
					tmpdata,err = strconv.ParseFloat(params.(string), 64)
						if err != nil {
							fmt.Printf("Parse Float err\n");
						}
		}
	return tmpdata;
}

func httpDo(method string,url string, param string) string {
client := &http.Client{}

		req, err := http.NewRequest(method, url, strings.NewReader(param))
			if err != nil {
				// handle error
			}
		var sign string = getSign(param)

			req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
			req.Header.Set("key", KEY)
			req.Header.Set("sign", sign)

			resp, err := client.Do(req)

			defer resp.Body.Close()

			body, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				// handle error
			}

		return string(body);
}

func marketlist() string {
	var url string = "http://data.gate.io/api2/1/marketlist"
		var ret string = string(httpGet(url))
		return ret
}

// 所有交易行情
func tickers() string {
	var url string = "http://data.gate.io/api2/1/tickers"
		var ret string = string(httpGet(url))
		return ret
}


// 单项交易行情
func ticker(ticker string) string {
	var url string = "http://data.gate.io/api2/1/ticker" + "/" + ticker
		ret := string(httpGet(url))
		return ret
}

func GateMarketToRedis(key string, wg *sync.WaitGroup){
	defer wg.Done()

	sdata := []byte(ticker(key))

	skey := "Gate_" + key

    //fmt.Printf("%s   %s \n", skey, sdata)
	err := client.Set(skey, sdata, 0).Err()
	if err != nil {
		fmt.Printf("Error: %s\n", err)
	}else{
		//fmt.Printf("Success write: %s\n", key)
	}

}


func GateMarketsToRedis(inWg *sync.WaitGroup) {
	defer inWg.Done()
	t := time.Now()	

	var data []byte = []byte(tickers())

	var mdata map[string]Detail

	err := json.Unmarshal(data, &mdata)
	if err != nil {
		fmt.Println("111error:", err)
	}

	var wg sync.WaitGroup
    
	for key, _ := range mdata {
		
		wg.Add(1)
        
		go GateMarketToRedis(key, &wg)
	}

	wg.Wait()

	fmt.Printf("GateMarketsToRedis duration: %s\n", time.Now().Sub(t))

}
